package cn.uce.cc.srv.biz.impl;


import cn.uce.base.ccos.*;
import cn.uce.base.page.Pagination;
import cn.uce.base.vo.*;
import cn.uce.cc.api.service.biz.*;
import cn.uce.cc.srv.client.CcosInterfaceClient;
import cn.uce.cc.srv.client.JsonHttpClient;
import cn.uce.common.omg.biz.IOmgEmpBiz;
import cn.uce.common.utils.StringUtils;
import cn.uce.core.cache.CacheManager;
import cn.uce.core.cache.base.ICache;
import cn.uce.service.biz.ICcSmOrderTypeBiz;
import cn.uce.utils.StringUtil;
import cn.uce.web.common.base.CurrentUser;
import cn.uce.web.common.util.WebUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


 /**
   * 创建工单接口
   * @Author liupan
   * @Description
   * @Date  2020-07-03 11:12
   */
@Service("ccosWorkOrderBiz")
public class CcosWorkOrderBiz implements ICcosWorkOrderBiz {
    private static final Logger log = LoggerFactory.getLogger(CcosWorkOrderBiz.class);


    @Value("${spring.serviceName.saveWorkBillInfo}")
    private String saveWorkBillInfo;
    @Value("${spring.serviceName.queryHistoryWorkBill}")
    private String queryHistoryWorkBill;
    @Value("${spring.serviceName.queryWorkBillDealRecord}")
    private String queryWorkBillDealRecord;
    @Resource
    CcosInterfaceClient ccosInterfaceClient;

    @Resource
    private ICcosOrgBiz ccosOrgBiz;

    @Resource
    private ICcosWaybillBiz ccosWaybillBiz;

    @Resource
    private ICcosUserBiz ccosUserBiz;
    @Resource
    private ISmOrderTypeBiz smOrderTypeBiz;
    @Resource
    private IOmgEmpBiz omgEmpBiz;
    /**
     * 新增工单
     * @param workOrderVo
     * @return
     * @throws Exception
     */
    @Override
    public String addWorkOrder(WorkOrderVo workOrderVo) {
        try {
            CurrentUser user = WebUtil.getCurrentUser();
            if (user != null && StringUtil.isNotBlank(user.getEmpCode())) {
                Map<String, Object> userInfo = ccosUserBiz.getUserInfo(user.getEmpCode());
                /** 放入工单所需字段 */
                workOrderVo.setUserName(user.getEmpName());
                workOrderVo.setCompCode((String) userInfo.get("compCode"));
                workOrderVo.setCompName((String) userInfo.get("compLongName"));
                workOrderVo.setDeptCode((String) userInfo.get("siteCode"));
                workOrderVo.setDeptName((String) userInfo.get("siteName"));
                workOrderVo.setUserCode((String) userInfo.get("userCode"));
            }
            workOrderVo.setDeptType("0");
            workOrderVo.setFromCompCode(workOrderVo.getFromCompCode());
            workOrderVo.setToCompCode(workOrderVo.getToCompCode());
            /** 重新放入任务部门name */
            String handleDepartmentCode = workOrderVo.getHandleDepartmentCode();
            Map<String, String> map = new HashMap<String, String>();
            map.put("keyWorkds", handleDepartmentCode);
            map.put("currentPage", "1");
            Pagination<WebPoint> WebPointMap = ccosOrgBiz.getWebPointsForWorkOrder(map);
            if (WebPointMap != null && WebPointMap.getData() != null && !WebPointMap.getData().isEmpty()) {
                List<WebPoint> webPoints1 = WebPointMap.getData();
                for (WebPoint wt : webPoints1) {
                    if (wt.getDeptCode().equals(handleDepartmentCode)) {
                        workOrderVo.setHandleDepartmentName(wt.getDeptName());
                    }
                }
            }
            /** 如果运单号不为空需要放入起始和中止网点 */
            if (StringUtil.isNotBlank(workOrderVo.getWayBillNo())) {
                /** 查询运单信息获取起始和中止网点 */
                String wayBillInfo = ccosWaybillBiz.getWayBillInfoByWBNo(workOrderVo.getWayBillNo());
                JSONObject jSONObject = JSONObject.parseObject(wayBillInfo);
                if (jSONObject != null) {
                    String str_api_temp = jSONObject.getString("data");
                    if (StringUtil.isBlank(str_api_temp)) {
                        throw new RuntimeException("查询运单信息获取起始和中止网点异常");
                    }
                    JSONObject jSONObject_temp = JSONObject.parseObject(str_api_temp);
                    String str_api_conver_temp = jSONObject_temp.getString("waybillExtendList");
                    if (StringUtil.isBlank(str_api_conver_temp)) {
                        throw new RuntimeException("查询运单信息获取起始和中止网点异常");
                    }
                    List<Object> lst = JSONObject.parseArray(str_api_conver_temp);
                    for (Object obj : lst) {
                        String str = obj.toString();
                        WaybillExtendVo waybillExtendVo = JSONObject.parseObject(str, WaybillExtendVo.class);
                        /** 放入起始和中止网点 */
                        workOrderVo.setStartPointCode(waybillExtendVo.getSourceZoneCode());
                        workOrderVo.setEndPointCode(waybillExtendVo.getDestZoneCode());
                    }
                }
            }
            Map<String, Object> params = new HashMap<>();
            params.put("serviceName", saveWorkBillInfo);
            params.put("parameters", new Object[]{workOrderVo});
            String returnMessage = null;
            String json = JsonHttpClient.postJsonForOpenPlatBridge(JSON.toJSONString(params));
            log.warn("addWorkOrder" + json);
            returnMessage = ccosInterfaceClient.queryOpenPlatFronBridge(json);
            log.warn("addWorkOrder" + returnMessage);
            if (null == returnMessage) {
                return null;
            }
            JSONObject resultMessage = JSONObject.parseObject(returnMessage);
            if ("true".equals(resultMessage.getString("success"))) {
                return resultMessage.getString("result");
            }
        } catch (Exception e) {
            log.warn("addWorkOrder", e);
            return e.toString();
        }
        return null;
    }

     @Override
     public Map<String,Object> getHistoryWorkOrder(WosWorkBillVo wosWorkBillVo) {
         if (StringUtils.isNullOrBlank(wosWorkBillVo.getWayBillNo())){
             return null;
         }else {
             wosWorkBillVo.setWayBillNo(wosWorkBillVo.getWayBillNo().trim());
         }
         Map<String, Object> params = new HashMap<>();
         params.put("serviceName", queryHistoryWorkBill);
         params.put("parameters", new Object[]{wosWorkBillVo});
         String result = "result";
         String msgTrue = "true";
         String success = "success";
         String returnMessage = null;
         ResultVo wbvList = null;
         Map<String,Object> map = new HashMap<>();
         List<WosWorkBillVo> processedList = new ArrayList<>();
         List<WosWorkBillVo> finishList = new ArrayList<>();
         try {
             String json  = JsonHttpClient.postJsonForOpenPlatBridge( JSON.toJSONString(params));
             log.info("工单历史查询接口请求"+json);
             returnMessage =  ccosInterfaceClient.queryOpenPlatFronBridge(json);
             log.info("工单历史查询接口响应"+returnMessage);
             if(null == returnMessage){
                 return null;
             }
             JSONObject resultMessage = JSONObject.parseObject(returnMessage);
             if(msgTrue.equals(resultMessage.getString(success))){
                 JSONObject resultList = JSONObject.parseObject(resultMessage.getString(result));
                 wbvList = JSON.parseObject(String.valueOf(resultList), ResultVo.class);
                 //查询所有大类
                 List<LittleBigTypeVo> btList = smOrderTypeBiz.queryComplaintTypeConf(0L);
                 Map<String,String> bigTypeMap = new HashMap<>();
                 Map<String,String> littleTypeMap = new HashMap<>();
                 for (LittleBigTypeVo bt : btList) {
                     bigTypeMap.put(String.valueOf(bt.getComplaintTypeConfId()), bt.getCauseType());
                     //根据所属大类查询小类
                     List<LittleBigTypeVo> ltList  = smOrderTypeBiz.queryComplaintTypeConf(Long.valueOf(bt.getComplaintTypeConfId()));
                     for (LittleBigTypeVo lt : ltList) {
                         littleTypeMap.put(String.valueOf(lt.getComplaintTypeConfId()), lt.getCauseType());
                     }
                 }
                 /**工单--状态类型**/
                 Map<String,String> statusTypeMap = new HashMap<>();
                 List<DirectionaryVo> statusTypeStr = smOrderTypeBiz.queryWorkOrderStatus();
//                 List<DirectionaryVo> stList = JSON.parseArray(statusTypeStr,KeyValueVo.class);
                 for (DirectionaryVo st:statusTypeStr) {
                     if(!StringUtils.isNullOrBlank(st.getKey())){
                         statusTypeMap.put(st.getKey(),st.getValue());
                     }
                 }
                 if("true".equals(wbvList.getSuccess())){
                     List<WosWorkBillVo> wwboList = wbvList.getData();
                     for (WosWorkBillVo wo:wwboList) {
                         wo.setComplaintBigTypeName(bigTypeMap.get(wo.getComplaintBigType()));
                         wo.setComplaintLittleTypeName(littleTypeMap.get(wo.getComplaintLittleType()));
                         if(StringUtil.isNotBlank(wo.getCreater())){
                             if(wo.getCreater().contains("@")){
                                 String createrNameObj = ccosUserBiz.getUserName(wo.getCreater());
                                 if("null".equals(createrNameObj)){
                                     wo.setCreaterName("");
                                 }else {
                                     UserNamesVo userNamesVo = JSON.parseObject(createrNameObj, UserNamesVo.class);
                                     if(userNamesVo != null){
                                         wo.setCreaterName(userNamesVo.getUserName());
                                     }
                                 }
                             }else{
                                 IcsEmpVo emp = omgEmpBiz.getEmpByCode(wo.getCreater());
                                 if(emp != null){
                                     wo.setCreaterName(emp.getEmpName());
                                 }
                             }
                         }
                         wo.setBillStatusName(statusTypeMap.get(wo.getBillStatus()));
                         if("5".equals(wo.getBillStatus())){
                             finishList.add(wo);
                         }else{
                             processedList.add(wo);
                         }
                     }
                 }
                 map.put("finishList",finishList);
                 map.put("processedList",processedList);
                 return map;
             }
         } catch (IOException e) {
             log.error("查询工单历史接口异常",e);
         } catch (Exception e) {
             log.error("查询工单历史接口异常",e);
         }
         return null;
     }

     @Override
     public WosWorkVo getDealRecords(FlowWorkBillVo flowWorkBillVo) {
         Map<String, Object> params = new HashMap<>();
         params.put("serviceName", queryWorkBillDealRecord);
         params.put("parameters", new Object[]{flowWorkBillVo});
         WosWorkVo wosWorkVo = new WosWorkVo();
         String result = "result";
         String msgTrue = "true";
         String success = "success";
         String returnMessage = null;
         try {
             String json  = JsonHttpClient.postJsonForOpenPlatBridge( JSON.toJSONString(params));
             log.info("工单历史查询接口请求"+json);
             returnMessage =  ccosInterfaceClient.queryOpenPlatFronBridge(json);
             log.info("工单历史查询接口响应"+json);
             if(null == returnMessage){
                 return null;
             }
             JSONObject resultMessage = JSONObject.parseObject(returnMessage);
             if(msgTrue.equals(resultMessage.getString(success))){
                 /**工单--处理类型**/
                 Map<String,String> dealTypeMap = new HashMap<>();
                 List<DirectionaryVo> kvList = smOrderTypeBiz.queryWosDealType();
                 if(kvList != null){
                     for (DirectionaryVo kv:kvList) {
                         if(!StringUtils.isNullOrBlank(kv.getKey())){
                             dealTypeMap.put(kv.getKey(),kv.getValue());
                         }
                     }
                 }
                 /**工单--流转类型**/
                 Map<String,String> flowTypeMap = new HashMap<>();
                 List<DirectionaryVo> ftList = smOrderTypeBiz.queryWosFlowType();
                 if(ftList != null){
                     for (DirectionaryVo ft:ftList) {
                         if(!StringUtils.isNullOrBlank(ft.getKey())){
                             flowTypeMap.put(ft.getKey(),ft.getValue());
                         }
                     }
                 }
                 wosWorkVo = JSON.parseObject(resultMessage.getString(result),WosWorkVo.class);
                 if("true".equals(wosWorkVo.getSuccess())){
                     List<WosWorkBillFlowLog> wosList = wosWorkVo.getData();
                     for (WosWorkBillFlowLog wbfg:wosList) {
                         //记录类型（1.处理记录2.流转记录）
                         if("1".equals(wbfg.getType())){
                             wbfg.setTypeName("处理记录");
                         }if("2".equals(wbfg.getType())){
                             wbfg.setTypeName("流转记录");
                         }
                         wbfg.setDealTypeName(dealTypeMap.get(wbfg.getDealType()));
                         wbfg.setFlowTypeName(flowTypeMap.get(wbfg.getFlowType()));
                     }
                 }
                 return wosWorkVo;
             }
         } catch (IOException e) {
             log.error("查询异常",e);
         } catch (Exception e) {
             log.error("查询异常",e);
         }
         return wosWorkVo;
     }
 }